package com.ccut.xunfeiSpringboot.service.impl;

import cn.xfyun.api.IatClient;
import cn.xfyun.model.response.iat.IatResponse;
import cn.xfyun.model.response.iat.IatResult;
import cn.xfyun.service.iat.AbstractIatWebSocketListener;
import com.ccut.xunfeiSpringboot.common.ListenerConfig;
import com.ccut.xunfeiSpringboot.service.ListenerService;
import okhttp3.Response;
import okhttp3.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.security.SignatureException;
import java.util.concurrent.CompletableFuture;

@Service
public class ListenerServiceImpl implements ListenerService {
    //    private static final String appId = "ba6cc2a0";
//    private static final String apiKey = "1a2835914ceb42b8c55689eec80f3f1a";
//    private static final String apiSecret = "NTA4YjQ3MWI1ZDJjZjFiMzVkZDMzYTNh";
    @Autowired
    private ListenerConfig listenerConfig;

    public CompletableFuture<String> transcribeAudio(File file) throws MalformedURLException, FileNotFoundException, SignatureException {
        // 创建语音识别客户端
        IatClient iatClient = new IatClient.Builder()
                .signature(listenerConfig.getAppid(), listenerConfig.getApiKey(), listenerConfig.getApiSecret())
                .build();

        // 用于存储最终识别结果
        CompletableFuture<String> resultFuture = new CompletableFuture<>();
        StringBuffer finalResult = new StringBuffer();

        // 发送文件进行语音识别
        iatClient.send(file, new AbstractIatWebSocketListener() {
            @Override
            public void onSuccess(WebSocket webSocket, IatResponse iatResponse) {
                if (iatResponse.getCode() != 0) {
                    resultFuture.completeExceptionally(new RuntimeException("识别失败: " + iatResponse.getMessage()));
                    return;
                }

                if (iatResponse.getData() != null && iatResponse.getData().getResult() != null) {
                    for (IatResult.Ws ws : iatResponse.getData().getResult().getWs()) {
                        for (IatResult.Cw cw : ws.getCw()) {
                            finalResult.append(cw.getW());
                        }
                    }

                    if (iatResponse.getData().getStatus() == 2) {
                        // 识别完成，返回结果
                        resultFuture.complete(finalResult.toString());
                        iatClient.closeWebsocket();
                    }
                }
            }

            @Override
            public void onFail(WebSocket webSocket, Throwable t, Response response) {
                resultFuture.completeExceptionally(t);
            }
        });

        return resultFuture;
    }
}
